
''' <summary>
''' Controller used to call the FileManager web service.
''' </summary>
''' <remarks>
''' All methods are meant to be called Async. and provide events to handle 
''' application flow. 
''' ITLackey 10.29.07
''' </remarks>
Public Class FileController


#Region "Events"

    Friend Event FolderCreated As EventHandler(Of NewFolderEventArgs)

    Friend Event FilesDeleting As EventHandler(Of DeleteFilesEventArgs)

    Friend Event FilesDeleted As EventHandler(Of DeleteFilesEventArgs)

    Friend Event FileInfoReceived As EventHandler(Of GetFileInfoEventArgs)

    Friend Event FileDownloaded As EventHandler(Of DownloadFileEventArgs)

    Friend Event FileDownloading As EventHandler(Of DownloadFileEventArgs)

    Friend Event FileUploaded As EventHandler(Of FileTransferEventArgs)

    Friend Event FileUploading As EventHandler(Of FileTransferEventArgs)

    Friend Event FolderListReceived As EventHandler(Of GetFoldersEventArgs)

    Friend Event FileListReceived As EventHandler(Of GetFilesEventArgs)

#End Region

    Friend Sub AddNewFolderAsync(ByVal args As NewFolderEventArgs)


        Try

            Using service As New IWeb.WebService

                service.IWebAuthendicationHeaderValue = args.Header

                service.AddFolder(args.FolderId, args.NewFolderName)


            End Using

            args.Status = args.NewFolderName & " was created."


        Catch ex As Exception

            args.HasError = True

            args.Status = ex.Message

        End Try

        RaiseEvent FolderCreated(Me, args)


    End Sub

    Friend Sub DeleteFilesAsync(ByVal args As DeleteFilesEventArgs)

        Try

            RaiseEvent FilesDeleting(Me, args)

            Using fileManager As New IWeb.WebService

                fileManager.IWebAuthendicationHeaderValue = args.Header


                args.Status = String.Format("{0} files deleted.", fileManager.DeleteFiles(args.FileIds))

            End Using

            args.HasError = False

        Catch ex As Exception

            args.HasError = True

            args.Status = ex.Message

        End Try

        RaiseEvent FilesDeleted(Me, args)

    End Sub

    Friend Sub DownloadFileAsync(ByVal args As DownloadFileEventArgs)

        args.Status = String.Format("Downloading {0}", args.FileName)

        RaiseEvent FileDownloading(Me, args)

        Try


            Dim fileContent As Byte()

            Using service As New IWeb.WebService

                service.IWebAuthendicationHeaderValue = args.Header

                fileContent = service.DownloadFile(args.FileId)

                If fileContent IsNot Nothing Then
                    IO.Directory.CreateDirectory(IO.Path.GetDirectoryName(args.FileName))

                    IO.File.WriteAllBytes(args.FileName, fileContent)

                End If

            End Using

            args.Status = "File saved to " & args.FileName

            args.HasError = False

        Catch ex As Exception

            args.Status = ex.Message

            args.HasError = True

        End Try

        RaiseEvent FileDownloaded(Me, args)


    End Sub

    Friend Sub GetFileListAsync(ByVal args As GetFilesEventArgs)

        Try

            Using fileManager As New IWeb.WebService

                fileManager.IWebAuthendicationHeaderValue = args.Header

                args.Files = New List(Of IWeb.IWebFileInfo) _
                    (fileManager.GetFilesByFolder(args.FolderId))

                args.Status = String.Format("{0} Files. {1}", args.Files.Count, _
                    fileManager.GetPortalSpaceUsed(True))

            End Using

            args.HasError = False

        Catch ex As Exception

            args.HasError = True

            args.Status = ex.Message

            args.Files = New List(Of IWeb.IWebFileInfo)


        End Try

        RaiseEvent FileListReceived(Me, args)


    End Sub

    Friend Sub GetFolderListAsync(ByVal args As GetFoldersEventArgs)

        Try

            Using fileManager As New IWeb.WebService

                fileManager.IWebAuthendicationHeaderValue = args.Header

                args.Folders = New List(Of IWeb.IWebFolderInfo) _
                    (fileManager.GetFoldersByParent(args.FolderId))


                args.Status = String.Format("{0} folders. {1}", args.Folders.Count, _
                    fileManager.GetPortalSpaceUsed(True))
            End Using

            args.HasError = False

        Catch ex As Exception

            args.HasError = True

            args.Status = ex.Message

            args.Folders = New List(Of IWeb.IWebFolderInfo)


        End Try

        RaiseEvent FolderListReceived(Me, args)


    End Sub

    Friend Sub GetFileInfoAsync(ByVal args As GetFileInfoEventArgs)

        Try

            Using service As New IWeb.WebService
                service.IWebAuthendicationHeaderValue = args.Header

                Dim info As IWeb.IWebFileInfo = service.GetFileById(args.FileId)

                args.File = info

            End Using

        Catch ex As Exception

            args.File = New IWeb.IWebFileInfo
            args.HasError = True
            args.Status = ex.Message

        End Try

        RaiseEvent FileInfoReceived(Me, args)

    End Sub

    Friend Sub UploadFileAsync(ByVal args As FileTransferEventArgs)


        args.Status = String.Format("Uploading {0}", args.FileName)

        RaiseEvent FileUploading(Me, args)

        Try

            Using service As New IWeb.WebService

                service.IWebAuthendicationHeaderValue = args.Header


                Dim maxRequestLength As Long = service.GetMaxRequestLength

                If (New IO.FileInfo(args.FileName).Length / 1024) > maxRequestLength Then

                    args.Status = "File too large maximum request length is: " & _
                       (maxRequestLength / 1024).ToString("0.00") & "MB"


                    args.HasError = True

                Else


                    Dim fileContent As Byte() = IO.File.ReadAllBytes(args.FileName)


                    args.Status = String.Format("Uploaded {1}. {0}", service.UploadFile _
                        (args.FolderId, IO.Path.GetFileName(args.FileName), fileContent), args.FileName)

                    args.HasError = False

                End If
            End Using

        Catch webEx As Net.WebException

            Select Case webEx.Status
                Case Net.WebExceptionStatus.MessageLengthLimitExceeded, _
                    Net.WebExceptionStatus.ProtocolError

                    args.Status = String.Format _
                        ("File {0} may have exceeded the maxium request length.", args.FileName)

                Case Net.WebExceptionStatus.SecureChannelFailure
                    args.Status = "Could not establish SSL connection."

                Case Net.WebExceptionStatus.Timeout
                    args.Status = String.Format("The request for file {0} has timed out.", args.FileName)

                Case Net.WebExceptionStatus.ConnectionClosed
                    args.Status = "Connection closed."

                Case Else
                    args.Status = webEx.Status.ToString


            End Select

            args.HasError = True


            My.Application.Log.WriteException(webEx, TraceEventType.Error, _
                "During uploading of " & args.FileName)


        Catch ex As Exception

            args.HasError = True

            args.Status = ex.Message


        End Try


        RaiseEvent FileUploaded(Me, args)


    End Sub

End Class
